package cn.tedu._07weibo.controller;

import cn.tedu._07weibo.base.response.JsonResult;
import cn.tedu._07weibo.base.response.StatusCode;
import cn.tedu._07weibo.mapper.UserMapper;
import cn.tedu._07weibo.pojo.dto.UserLoginParam;
import cn.tedu._07weibo.pojo.dto.UserRegParam;
import cn.tedu._07weibo.pojo.entity.User;
import cn.tedu._07weibo.pojo.vo.UserVo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("v1/user/")
@Slf4j
@Tag(name = "用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("reg")
    @Operation(summary = "用户注册")
    @ApiOperationSupport(order = 10)
    public JsonResult userReg( @RequestBody @Validated UserRegParam userRegParam){
        log.debug("开始处理用户注册功能");
        String username=userRegParam.getUsername();
        int rows=userMapper.CheckUserByUsername(username);
        if (rows>0){
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user=new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        return JsonResult.ok(userMapper.RegUserById(user));
    }

    @PostMapping("login")
    @Operation(summary = "用户登录")
    @ApiOperationSupport(order = 20)
    public JsonResult userLogin(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        log.debug("开始处理用户登录功能"+userLoginParam);
        UserVo userVo=userMapper.loginByUsernameAndPassword(userLoginParam);
        if(userVo==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVo);
        return JsonResult.ok(userVo);
    }
    @GetMapping("currentUser")
    @Operation(summary = "获取当前用户")
    @ApiOperationSupport(order = 30)
    public JsonResult getCurrentUser(HttpSession session){
        log.debug("开始获取当前用户"+session);
        UserVo user = (UserVo)session.getAttribute("user");
        log.debug("UserVo"+user);
        if(user==null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        return JsonResult.ok(user.getUsername());

    }

}
